package com.lan.workflow.exception;

import com.lan.workflow.common.ResponseCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2020/6/3.
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String, Object> defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
        logger.error("---BaseException Handler---Host {} invokes url {} ERROR: ",request.getRemoteHost(),request.getRequestURL(),e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", ResponseCodeEnum.INTERNAL_SERVER_ERROR.getKey());
        result.put("msg", "遇到未知异常，请稍后重试");
        result.put("errorMessage", e.getMessage() == null ? e.getClass() : e.getMessage());
        if(e instanceof MaxUploadSizeExceededException){
            result.put("code", ResponseCodeEnum.INTERNAL_SERVER_ERROR.getKey());
            result.put("msg", "文件太大了！");
        } else if(e instanceof HttpRequestMethodNotSupportedException){
            result.put("code", ResponseCodeEnum.INTERNAL_SERVER_ERROR.getKey());
            result.put("msg", "请换一种请求方式GET/POST");
        }
        return result;
    }

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Map<String, Object> jsonErrorHandle(HttpServletRequest request, BaseException e) {
        logger.error("---BaseException Handler---Host {} invokes url {} ERROR: ", request.getRemoteHost(), request.getRequestURL(), e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", e.getCode());
        result.put("msg", e.getMessage());
        result.put("errorMessage", e.getMessage() == null ? e.getClass() : e.getMessage());
        return result;
    }
}
